﻿var Colorbox4Sitecore = window.Colorbox4Sitecore || {};
var tId;

Colorbox4Sitecore.initColorbox = function (config) {
    var colorboxConfig = {
        href: config.href,
        width: config.width,
        height: config.height,
        opacity: config.opacity,
        iframe: true,
        onOpen: function () {
            //Cancel the previous timeout
            if (tId != "undefined") {
                clearTimeout(tId);
            }
        },
        onComplete: function () {
            var colorb = $("#colorbox");

            colorb.css({ border: "solid 2px " + config.borderColor });

            colorb.animate({ "left": "+=" + config.moveLeft, "top": "+=" + config.moveTop }, config.speed);

            if (config.hasTimeout) {
                tId = setTimeout(function () {
                    if (config.fadeOutPath) {
                        colorb.animate({ "left": "-=" + config.moveLeft, "top": "-=" + config.moveTop }, config.speed, function () {
                            $.colorbox.close();
                        });
                    } else {
                        $.colorbox.close();
                    }
                }, config.fadeOutTime);
            }
            replaceClickEvent(config.fadeOutPath, config.moveLeft, config.moveTop, config.speed);
        }
    };

    if (config.top != "") {
        colorboxConfig.top = config.top;
    }

    if (config.left != "") {
        colorboxConfig.left = config.left;
    }

    if (config.close != "") {
        colorboxConfig.close = config.close;
    }

    
    $(config.selector).colorbox(colorboxConfig);
    
    if(config.showAutomatically) {
        setTimeout(function() {
            $.colorbox(colorboxConfig);
        }, config.Delay);
    }
};

function replaceClickEvent(animate, moveLeft, moveTop, speed) {
    var clickEvents = $('#cboxClose').data("events").click;
    $.each(clickEvents, function(key, handlerObj) {
        $('#cboxClose').unbind('click', handlerObj.handler);
                                                             
        $('#cboxClose').bind('click', function() {
            if(tId != "undefined")
            {
                clearTimeout(tId);
            } 

            if(animate) {
                $("#colorbox").animate({ "left": "-=" + moveLeft, "top": "-=" + moveTop }, speed, function () {
                $.colorbox.close();
            });          
            } else {
                $.colorbox.close();
            }                                                                  
        });
    });
}